package com.fgchen.study.thread;

import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created by fgchen on 2017/7/21.
 */
public class ForkJoinDemo {

    public static void main(String[] args) throws Exception {

        ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());

        HashSet<String> set = new HashSet<String>();
        Future<Integer> future = pool.submit(new MyTask(1, 10000, set));

        System.out.println(future.get());

        for (String name : set) {
            System.out.println(name);
        }

    }

    public static class MyTask extends RecursiveTask<Integer> {

        private int start;
        private int end;

        private HashSet<String> set;

        public MyTask(int start, int end, HashSet<String> set) {
            this.start = start;
            this.end = end;
            this.set = set;
        }

        @Override
        protected Integer compute() {
            set.add(Thread.currentThread().getName());
            int sum = 0;
            if (end - start < 10) {
                for (int i = start; i <= end; i++) {
                    sum += i;
                }
            } else {
                int mid = (start + end) / 2;
                MyTask left = new MyTask(start, mid, this.set);
                MyTask right = new MyTask(mid + 1, end, this.set);

                sum += left.fork().join();
                sum += right.fork().join();
            }
            return sum;
        }
    }

}
